<template>
  <el-dialog :title="title || '导入模板'" v-model="visible" width="600px" @close="cancelDialog">
    <el-form ref="formRef">
      <el-form-item label="选择文件">
        <el-upload ref="uploadRef" :limit="1" :file-list="fileList" :drag="true" :before-upload="handleBeforeUpload"
          style="width: 100%;" :on-remove="handleFileRemove" :http-request="handleUpload" :loading="uploadLoading"
          v-bind="attrs">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            拖拽到这里或者 <em>点击上传</em>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="下载模板">
        <el-button size="default" type="text" @click="downloadTemplate" :loading="downloading">
          点击下载模板
        </el-button>
      </el-form-item>
    </el-form>
    <div class="mt-3 text-sm text-gray-700">
      <div>提示：为方便导入，请先下载导入模板文件；{{ tips }}</div>
    </div>
    <template #footer>
      <el-button type="primary" @click="cancelDialog" :loading="submitLoading">
        关闭
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { downloadImport, uploadImport } from '@/apis/global'
import { blobDownload } from '@/utils/file'
import { useAttrs } from 'vue'

const attrs = useAttrs()
// 定义props
const props = defineProps({
  exportUrl: {
    type: String,
    required: false
  },
  uploadUrl: {
    type: String,
    required: false
  },
  title: {
    type: String,
    default: '导入模板'
  },
  tips: {
    type: String,
    default: ''
  },
  maxSize: {
    type: Number,
    default: 100
  },
  // 是否自动关闭弹窗
  // 开启后上传成功后自动关闭，点击关闭自动关闭
  autoClose: {
    type: Boolean,
    default: false
  },
  // 成功后的钩子函数
  successAfter: Function,
  // 失败后
  errorAfter: Function
})

const visible = defineModel()
// 定义emits
const emits = defineEmits(['update:visible', 'done'])

const formRef = ref(null)
const uploadRef = ref(null)
const fileList = ref([])
const submitLoading = ref(false)
const downloading = ref(false)
const uploadLoading = ref(false)
const exportType = ref(1) // 导出方式,接口导出为1,阿里云链接为2

// 下载模板
const downloadTemplate = async () => {
  if (downloading.value) return

  const url = props.exportUrl
  if (exportType.value === 1) {
    downloading.value = true
    try {
      const res = await downloadImport(url)
      blobDownload(res)
    } catch (error) {
      ElMessage.error('下载模板失败')
    } finally {
      downloading.value = false
    }
  }
}

// 上传文件
const handleUpload = (params) => {
  uploadLoading.value = true
  const formData = new FormData()
  formData.append('file', params.file)
  uploadImport(props.uploadUrl, formData)
    .then(res => {
      if (!res.success) {
        uploadLoading.value = false
        fileList.value.pop()
        ElMessage.error(res.message || '上传失败')
        props.errorAfter && props.errorAfter()
      } else {
        uploadLoading.value = false
        setTimeout(() => {
          ElMessage.success('导入成功')
          cancelDialog()
          props.successAfter && props.successAfter()
        }, 500)
        fileList.value = []
        emits('done')
      }
    })
    .catch(error => {
      uploadLoading.value = false
      fileList.value.pop()
      ElMessage.error('上传失败')
    })
}

// 文件移除处理
const handleFileRemove = (file, list) => {
  fileList.value = list
}

// 上传前校验
const handleBeforeUpload = (file) => {
  const isRightSize = file.size / 1024 / 1024 < props.maxSize
  if (!isRightSize) {
    ElMessage.error(`文件大小超过 ${props.maxSize}MB`)
  }
  return isRightSize
}

// 关闭对话框
const cancelDialog = () => {
  fileList.value = []
  props.autoClose && (visible.value = false)
  emits('done')
}

// 监听对话框显示状态，重置文件列表
watch(() => visible.value, (newVal) => {
  if (!newVal) {
    fileList.value = []
  }
})

// 组件卸载时清理
onUnmounted(() => {
  fileList.value = []
})
</script>

<style scoped>
/* 可以在这里添加自定义样式 */
</style>
